//
//  HomeViewController.m
//  CarUser
//
//  Created by 王森林 on 2018/11/29.
//  Copyright © 2018年 王森林. All rights reserved.
//

#import "HomeViewController.h"
#import "HomADCell.h"
#import "HomeServiceCell.h"
#import "HomeFuntionCell.h"
#import "HomeCarTypeCell.h"
#import "HomeHotCell.h"
#import "HomeCommonCell.h"
#import "HomeCollectViewController.h"
#import "HomeMessagePageViewController.h"
#import "HomeSearchViewController.h"

#import "Car_CarDetailViewController.h"
@interface HomeViewController ()<UITextFieldDelegate>
@property (strong, nonatomic) NSArray *imgsAry;   //顶部bar滚动
@property (strong, nonatomic) NSArray *functionAry; //功能模块
@property (strong, nonatomic) NSArray *carTypeAry; //热门车型
@property (strong, nonatomic) NSMutableArray  *carHotAry;  //热销车型

@property (strong, nonatomic)  UIView *titleView;
@property (strong, nonatomic) UIView *searchView;
@property (strong, nonatomic) UIButton *messageBtn;
@property (strong, nonatomic) UIButton *favoriteBtn;
@end

@implementation HomeViewController

- (BOOL )fd_prefersNavigationBarHidden{
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createNavUI];
    [self createUI];
    [self fetchDataFromNet];
    self.mainTableView.mj_header = [Custom_Mjfresh mj_customMjfreshHeaderSetting:^{
        [self fetchDataFromNet];
    }];
    // Do any additional setup after loading the view.
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    self.titleView.frame =  CGRectMake(0, IS_IPHONE_X?20:0, BOUNDWIDTH, IS_IPHONE_X?68:64);
    
}

- (void)fetchDataFromNet
{
    //获取广告顶部
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"PZLXDM"],
                             @"PZLXDM":@"2"
                           
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_28 params:params md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
         [self.mainTableView.mj_header endRefreshing];
      
        NSDictionary *resultDict  = response;
        self.imgsAry  = [resultDict objectForKey:@"list"];
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
        [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
             [self.mainTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
    //获取重点车型
    NSDictionary *params1 = @{
                             @"FKEY":[CommonMethod createMD5Key:@"NULL"],
                             @"SFZD00":@"1"
                             
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_9 params:params1 md5Paraname:nil success:^(id  _Nullable response) {
         [self.mainTableView.mj_header endRefreshing];
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        NSDictionary *resultDict  = response;
        self.carTypeAry  = [resultDict objectForKey:@"list"];
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];
        [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
             [self.mainTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
    //获取热销排行
    NSDictionary *params2 = @{
                              @"FKEY":[CommonMethod createMD5Key:@"NULL"],
                              @"sfrx00":@"1",
                              @"showCount":@"10"
                              };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_getSaleCarList params:params2 md5Paraname:nil success:^(id  _Nullable response) {
         [self.mainTableView.mj_header endRefreshing];
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
        
        NSDictionary *resultDict  = response;
        self.carHotAry  = [NSMutableArray arrayWithArray:[resultDict objectForKey:@"list"]];
        [self.mainTableView reloadData];
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
             [self.mainTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
    
    
    
    
    
}

- (void)createUI
{
    
     self.mainTableView.frame  = CGRectMake(0, 0, BOUNDWIDTH, BOUNDHEIGHT-TABBAR_HEIGHT);
     [self.mainTableView registerClass:[HomADCell class] forCellReuseIdentifier:@"HomADCell"];
     [self.mainTableView registerClass:[HomeServiceCell class] forCellReuseIdentifier:@"HomeServiceCell"];
     [self.mainTableView registerClass:[HomeFuntionCell class] forCellReuseIdentifier:@"HomeFuntionCell"];
     [self.mainTableView registerClass:[HomeCarTypeCell class] forCellReuseIdentifier:@"HomeCarTypeCell"];
     [self.mainTableView registerClass:[HomeHotCell class] forCellReuseIdentifier:@"HomeHotCell"];
     [self.mainTableView registerClass:[HomeCommonCell class] forCellReuseIdentifier:@"HomeCommonCell"];
}

#pragma mark - UI相关
- (void)createNavUI{
//
//    self.navigationController.navigationBar.translucent = NO;
//    self.navigationController.navigationBar.shadowImage = [UIImage new];
    
 
    if (!self.titleView) {
        self.titleView = [[UIView alloc] initWithFrame:CGRectMake(0, IS_IPHONE_X?20:0, BOUNDWIDTH, IS_IPHONE_X?68:64)];
        [self.view addSubview:self.titleView];
    }
    
//    CGFloat navHeight = 44;
//    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BOUNDWIDTH - kMarginLeft - kMarginRight, navHeight)];
//    self.navigationItem.titleView = titleView;

//    titleView.backgroundColor = [UIColor redColor];
   
    
    //WithFrame:CGRectMake(0, 5, BOUNDWIDTH-kMarginLeft-kMarginRight-80, 30)
    self.searchView = [[UIView alloc]  initWithFrame:CGRectMake(20, 25, BOUNDWIDTH-kMarginLeft-kMarginRight-80, 30)];
    self.searchView.backgroundColor = [UIColor whiteColor];
    self.searchView.layer.cornerRadius =15;
    self.searchView.layer.masksToBounds = YES;
    [self.titleView addSubview:self.searchView];
    
    UIImage *searchImage = IMG(@"home_search");
    UIImageView *searchImageView = [[UIImageView alloc] initWithImage:searchImage];
    [self.searchView addSubview:searchImageView];
    [searchImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.searchView.mas_left).offset(8);
        make.width.mas_equalTo(IMGWIDTH(searchImage));
        make.height.mas_equalTo(IMGHEIGHT(searchImage));
        make.centerY.mas_equalTo(self.searchView.mas_centerY);
    }];
    

    UITextField *searchField = [UITextField new];
    searchField.text = @"搜索品牌/车型/经销商";
    //搜索品牌/车型/经销商
    searchField.font = FONT_SIZE(12);
    searchField.textColor = Common_TextLowColor;
    searchField.delegate = self;
    [self.searchView addSubview:searchField];
    [searchField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(searchImageView.mas_right).offset(9);
        make.right.mas_equalTo(self.searchView.mas_right).offset(-8);
        make.height.mas_equalTo(30);
        make.centerY.mas_equalTo(self.searchView.mas_centerY);
    }];
    
    
    
    UIImage *favoriteImage = IMG(@"home_favorite");
    self.favoriteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.favoriteBtn setImage:favoriteImage forState:UIControlStateNormal];
    [self.favoriteBtn addTarget:self action:@selector(favoriteAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.titleView addSubview:self.favoriteBtn];
    [self.favoriteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.searchView.mas_right).offset(14);
        make.width.mas_equalTo(34);
        make.height.mas_equalTo(34);
        make.centerY.mas_equalTo(self.searchView.mas_centerY);
    }];
    
    
    UIImage *messageImage = IMG(@"home_message");
   self.messageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.messageBtn setImage:messageImage forState:UIControlStateNormal];
    [self.messageBtn addTarget:self action:@selector(messageAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.titleView addSubview:self.messageBtn];
    [self.messageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.favoriteBtn.mas_right).offset(0);
        make.width.mas_equalTo(34);
        make.height.mas_equalTo(34);
        make.centerY.mas_equalTo(self.searchView.mas_centerY);
    }];
    
    
}

#pragma mark ----UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == self.mainTableView) {
        CGFloat y = scrollView.contentOffset.y;
        if (y > 0) {
            if (y - 60 > (IS_IPHONE_X ? 88 + 60: 64 + 60)) {
                self.titleView.backgroundColor = [UIColor whiteColor];
                self.searchView.backgroundColor = Common_Head_Color;
                self.messageBtn.contentMode  = UIViewContentModeScaleToFill;
                [self.messageBtn setImage:IMG(@"home_message1") forState:UIControlStateNormal];
                self.favoriteBtn.contentMode  = UIViewContentModeScaleToFill;
                [self.favoriteBtn setImage:IMG(@"home_favorite1") forState:UIControlStateNormal];
                
            }else{
//                self.titleView.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:(y - 60)/(IS_IPHONE_X ? 88 + 60: 64 + 60)];
                
            }
            
            
            
        }else{
            self.titleView.backgroundColor = [UIColor clearColor];
            self.searchView.backgroundColor = [UIColor whiteColor];
            [self.messageBtn setImage:IMG(@"home_message") forState:UIControlStateNormal];
             [self.favoriteBtn setImage:IMG(@"home_favorite") forState:UIControlStateNormal];
            
            //            CGFloat sacle = fabs(y)*3/self.headerBgImgv.height + 1;
            //            //            self.headerBgImgv.transform = CGAffineTransformTranslate(CGAffineTransformIdentity,0, 0);
            //            self.headerBgImgv.transform = CGAffineTransformMakeScale(1.0, sacle);
        }
    }
    
    
}



//进入收藏界面
- (void)favoriteAction:(id)sender
{
    UserRes *user = [CommonMethod getUser];
    if (!user) {
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
        return;
    }
    HomeCollectViewController  *control  = [[HomeCollectViewController alloc] init];
    control.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:control animated:YES];
    
}

//进入消息界面
- (void)messageAction:(id)sender
{
    HomeMessagePageViewController *control = [[HomeMessagePageViewController alloc] init];
    control.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:control animated:YES];
    
}


//- (NSArray *)imgsAry {
//    if (!_imgsAry) {
//        _imgsAry = @[@"car_test1",@"car_test2",@"car_test3"];
//    }
//    return _imgsAry;
//
//}

- (NSArray *)functionAry {
    if (!_functionAry) {
        _functionAry = @[@{@"imageName":@"home_port",@"title":@"维修保养"},
                         @{@"imageName":@"home_service",@"title":@"保险服务"},
                         @{@"imageName":@"home_quelity",@"title":@"质量三包"},
                         @{@"imageName":@"home_offline",@"title":@"线下体验"},
                         ];
    }
    return _functionAry;
    
}

//- (NSArray *)carTypeAry {
//    if (!_carTypeAry) {
//        _carTypeAry = @[@"car_test1",@"car_test2"];
//    }
//    return _carTypeAry;
//
//}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    //失去焦点
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    HomeSearchViewController *control = [[HomeSearchViewController alloc] init];
    control.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:control animated:YES];
    
}


#pragma mark - 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5+self.carHotAry.count;
}
#pragma mark - 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:
            {
                return 230.0f;
            }
            break;
        case 1:
        {
            return 105.0f;
        }
            break;
        case 2:
        {
            return 130.0f;
        }
            break;
        case 3:
        {
            return 167.0f;
        }
            break;
        case 4:
        {
            return 48.0f;
        }
            break;
            
        default:
            return 128.0f;
            break;
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:
           {
               
               HomADCell *cell = (HomADCell *)[tableView dequeueReusableCellWithIdentifier:@"HomADCell" forIndexPath:indexPath];
               [cell setData:self.imgsAry];
               cell.selectionStyle = UITableViewCellSelectionStyleNone;
               return cell;
           }
            break;
        case 1:
        {
            
            HomeServiceCell *cell = (HomeServiceCell *)[tableView dequeueReusableCellWithIdentifier:@"HomeServiceCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
//            [cell setDataAry:self.imgsAry];
            return cell;
        }
            break;
        case 2:
        {
            
            HomeFuntionCell *cell = (HomeFuntionCell *)[tableView dequeueReusableCellWithIdentifier:@"HomeFuntionCell" forIndexPath:indexPath];
            [cell setData:self.functionAry];
            cell.pushType = 1;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case 3:
        {
            
            HomeCarTypeCell *cell = (HomeCarTypeCell *)[tableView dequeueReusableCellWithIdentifier:@"HomeCarTypeCell" forIndexPath:indexPath];
            [cell setData:self.carTypeAry];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case 4:
        {
            
            HomeHotCell *cell = (HomeHotCell *)[tableView dequeueReusableCellWithIdentifier:@"HomeHotCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
//            [cell setData:self.carTypeAry];
            return cell;
        }
            break;
            
            
        default:
        {
            HomeCommonCell *cell = (HomeCommonCell *)[tableView dequeueReusableCellWithIdentifier:@"HomeCommonCell" forIndexPath:indexPath];
            [cell setData:self.carHotAry[indexPath.row - 5]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        }
            break;
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row > 4) {
        Car_CarDetailViewController *push = [[Car_CarDetailViewController alloc]init];
        NSDictionary  *dict = self.carHotAry[indexPath.row - 5];
        push.SERIES_ID = [dict objectForKey:@"SALECAR_ID"];
        [self.navigationController pushViewController:push animated:YES];
    }
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
